package org.mirrentools.attendance.console;

import org.mirrentools.attendance.console.common.Constant;
import org.mirrentools.attendance.console.router.RecordRouter;
import org.mirrentools.attendance.console.router.ReportRouter;
import org.mirrentools.attendance.console.router.UsersRouter;
import org.mirrentools.attendance.console.service.SecurityHandler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.assist.SQLExecute;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 程序入口
 *
 * @author <a href="http://szmirren.com">Mirren</a>
 */
public class MainVerticle extends AbstractVerticle {
  public static void main(String[] args) {
    MainLauncher.start();
  }

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    Router router = Router.router(vertx);
    router.route().handler(CorsHandler.create("*"));
    router.route().handler(BodyHandler.create());
//		router.route("/*").handler(StaticHandler.create("webroot").setDefaultContentEncoding("UTF-8"));
//		router.route("/").handler(rct -> rct.response().setStatusCode(302).putHeader("Location", "/static/index.html").end());
    JDBCClient jdbcClient = JDBCClient.createShared(vertx, config().getJsonObject(Constant.CONFIG_DB));
    SQLExecute<JDBCClient> execute = SQLExecute.createJDBC(jdbcClient);
    Map<String, Boolean> filterMap = new HashMap<>();
    SecurityHandler securityHandler = SecurityHandler.create(vertx, filterMap, jdbcClient);
    router.route("/api/*").handler(securityHandler::authToken);

    SecurityHandler securityHandlerAdmin = SecurityHandler.createAdmin(vertx, filterMap, jdbcClient);
    router.route("/admin/api/*").handler(securityHandlerAdmin::authToken);

    UsersRouter.startService(router, execute);
    ReportRouter.startService(router, execute);
    RecordRouter.startService(router, execute);

    vertx.createHttpServer().requestHandler(router).listen(config().getInteger(Constant.CONFIG_HTTP_PORT), res -> {
      if (res.succeeded()) {
        System.out.println("server running port:" + config().getInteger(Constant.CONFIG_HTTP_PORT));
        startPromise.complete();
      } else {
        startPromise.fail(res.cause());
      }
    });
  }
}
